package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/valid-tic-tac-toe-state/">794. 有效的井字游戏</a>
 */
public class Solution794 extends BaseSolution {

    public boolean validTicTacToe(String[] board) {
        int countX = 0, countO = 0;
        for (String s : board) {
            for (int i = 0; i < 3; i++) {
                char c = s.charAt(i);
                countX += c == 'X' ? 1 : 0;
                countO += c == 'O' ? 1 : 0;
            }
        }
        if (countX != countO && countX - 1 != countO) {
            return false;
        }

        int[][] f = new int[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                char c = board[i].charAt(j);
                f[i][j] = c == ' ' ? 0 : c == 'X' ? 1 : -1;
            }
        }
        boolean okO = false;
        boolean okX = false;
        for (int i = 0; i < 3; i++) {
            int c1 = 0, c2 = 0;
            for (int j = 0; j < 3; j++) {
                c1 += f[i][j];
                c2 += f[j][i];
            }
            if (c1 == -3 || c2 == -3) {
                okO = true;
            }
            if (c1 == 3 || c2 == 3) {
                okX = true;
            }
        }
        int c1 = 0, c2 = 0;
        for (int i = 0; i < 3; i++) {
            c1 += f[i][i];
            c2 += f[i][2 - i];
        }
        okO = okO || c1 == -3 || c2 == -3;
        okX = okX || c1 == 3 || c2 == 3;
        if (countX - 1 == countO) {
            // x 比 o 多一个，那 o 不能成， x 无所谓，任何行列 斜边 和 不能等于 -3
            return !okO;
        } else {
            return !okX;
        }
    }

    public static void main(String[] args) {
        Solution794 solution = new Solution794();
        System.out.println(solution.validTicTacToe(new String[]{"XOX","O O","XOX"}));
    }
}